/*
 * MeshGroup.cpp
 *
 *  Created on: 01/11/2011
 *      Author: faust
 */

#include "MeshGroup.h"
#include "SampleUtils.h"

MeshGroup::MeshGroup()
{

}

MeshGroup::~MeshGroup()
{
	if (indices != 0) delete[]indices;

	if (texture != 0) delete texture;
}

MeshGroup* MeshGroup::create(JNIEnv* env, jobject jMeshGroupObject)
{
	MeshGroup* group = new MeshGroup();
	group->indices = UtilsJNI::getJavaIntArray(env, jMeshGroupObject, "getIndices", "MeshGroup::create");

	jclass jMeshGroupClass = env->GetObjectClass(jMeshGroupObject);

	//Check whether the group has texture or not
	jmethodID hasTextureMethodID = env->GetMethodID(jMeshGroupClass,
			"hasTexture", "()Z");
	if (hasTextureMethodID == 0)
	{
		LOG("MeshGroup::create - Function hasTexture() not found.");
		return NULL;
	}

	jboolean hasTex = env->CallBooleanMethod(jMeshGroupObject, hasTextureMethodID);
	group->hasTexture = hasTex;

	//Read indicesCount
	jmethodID getIndicesCountMethodID = env->GetMethodID(jMeshGroupClass,
		"getIndicesCount", "()I");
	if (getIndicesCountMethodID == 0)
	{
		LOG("MeshGroup::create - Function getIndicesCount() not found.");
		return NULL;
	}

    int indicesCount = env->CallIntMethod(jMeshGroupObject, getIndicesCountMethodID);
    if (!indicesCount)
    {
        LOG("MeshGroup::create - getIndicesCount() returned zero.");
    }
	group->indicesCount = indicesCount;

	// Load texture if needed
	if (group->hasTexture) loadTexture(env, jMeshGroupObject, group);
	else group->texture = NULL;

	return group;
}

void MeshGroup::loadTexture(JNIEnv* env, jobject jMeshGroupObject, MeshGroup* group)
{
	jclass jMeshGroupClass = env->GetObjectClass(jMeshGroupObject);

    jmethodID getTextureMethodID = env->GetMethodID(jMeshGroupClass,
        "getTexture", "()Lcom/EdificacioAR/Texture;");
    if (getTextureMethodID == 0)
    {
        LOG("MeshGroup::create - Function getTexture() not found.");
        return;
    }

	jobject textureObject = env->CallObjectMethod(jMeshGroupObject, getTextureMethodID);
	if (textureObject == NULL)
	{
		LOG("MeshGroup::create - GetTexture() returned zero pointer");
		return;
	}

	group->texture = Texture::create(env, textureObject);
	//LOG("MeshGroup::create - Texture created");

}
